'use strict';

import {ajax, nameSpace } from 'utils/index';
import jsonp from 'jsonp';

let ns = nameSpace('Zhekou1');

export const SET_FIELD = ns('SET_FIELD');
export const SET_ZHEKOU_TYPE = ns('SET_ZHEKOU_TYPE');
export const CREAT_ZHEKOU_START = ns('CREAT_ZHEKOU_START');
export const CREAT_ZHEKOU_SET_ITEMS = ns('CREAT_ZHEKOU_SET_ITEMS');
export const CREAT_ZHEKOU_NEED_ITEMS = ns('CREAT_ZHEKOU_NEED_ITEMS');
export const CREAT_ZHEKOU_DONE = ns('CREAT_ZHEKOU_DONE');
export const CREAT_ZHEKOU_ERR = ns('CREAT_ZHEKOU_ERR');
export const CLOSE_DIALOG = ns('CLOSE_DIALOG');

export function setField(name,value) {
  return {type: SET_FIELD,name: name,value:value};
}
export function setZhekouType(value) {
  return {type: SET_ZHEKOU_TYPE,value:value};
}
export function closeDialog() {
  return {type: CLOSE_DIALOG,visible:false};
}
export function stepNeedItems() {
  return {type: CREAT_ZHEKOU_NEED_ITEMS,needItems:false};
}
export function createZhekou(params) {
    return (dispatch) => {
    //发送请求前
    dispatch({
      type: CREAT_ZHEKOU_START,
      data: params
    });
	if(window.workbench){
		//千牛环境执行创建折扣,含有workbench参数为千牛环境
		  window.QN.top.invoke( {
				cmd : 'taobao.promotionmisc.item.activity.add',
				param : params,
				method:"post",
				success : function(rsp, cmd, param) {
					console.log(rsp,param);
				},
				error : function(msg, cmd, param) {
					console.log(msg,param);
				}
			} );
	}else{
		//web环境执行创建折扣
		ajax({
			  api: 'createShopActive',
			  method: 'GET',
			  data:params
			},(json) => {
			  //成功后
			  if(params.itemArea=="some"){
				  //部分商品参与，要进入设置商品环节，暂存活动ID
				  sessionStorage.setItem("activityId", json.activity_id); //使用本地存储activeId
				  dispatch({
					type: CREAT_ZHEKOU_SET_ITEMS,
					activityId: json.activity_id,
					needItems:true,
					actionDone:false
				  });
			  }else{
				  //全店参与的，进入最后一个环节，暂存活动ID
				  dispatch({
					type: CREAT_ZHEKOU_DONE,
					activityId: json.activity_id,
					actionDone:true
				  });
			  }

			},(json) => {
			  //失败后
			  //(json.code==53) W2超时
			  const login = (json.code==210);
			  
			  dispatch({
				type: CREAT_ZHEKOU_ERR,
				message:json.msg+(json.sub_msg?json.sub_msg:""),
				loginFalse:login
				});
		});
	}

  };
}


